package org.example.comment.service.Impl;

import org.example.cassell_client.service.UserServiceClient;
import org.example.comment.entity.Comment;
import org.example.comment.entity.vo.CommentVO;
import org.example.comment.repository.CommentRepository;
import org.example.comment.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@EnableFeignClients(basePackages = "org.example.cassell_client.service")
public class CommentServiceImpl implements CommentService {
    private final CommentRepository commentRepository;
    private final UserServiceClient userServiceClient;

    public CommentServiceImpl(CommentRepository commentRepository, UserServiceClient userServiceClient) {
        this.commentRepository = commentRepository;
        this.userServiceClient = userServiceClient;
    }

    @Override
    @CacheEvict(value = "CommentCache", allEntries = true, beforeInvocation = true)
    public void addComment(Comment comment) {
        commentRepository.addComment(comment);
        commentRepository.addTipComment(comment);
    }

    @Cacheable(value = "CommentCache", sync = true)
    public List<CommentVO> getComment(Integer TipId) {
        // 1. 获取评论列表
        List<CommentVO> commentList = commentRepository.getComment(TipId);

        // 2. 遍历评论列表，查询用户信息并组合
        for (CommentVO comment : commentList) {
            String userInfo =userServiceClient.getUserInfo(comment.getUserEmail());
            if (userInfo != null) {
                comment.setUserName(userInfo);
            }
        }

        return commentList;
    }
}
